<template>
  <view class="video-container">
    <swiper class="video-swiper" vertical="true" @change="onSwipeChange" :current="currentVideoIndex">
      <swiper-item v-for="(video, index) in videoList" :key="video.id || index">
        <view class="video-item">
          <!-- 视频封面（播放时不渲染，避免覆盖原生视频层） -->
          <image
            v-if="video.showCover"
            class="video-cover"
            :src="video.coverUrl"
            mode="aspectFill"
            @click="playVideo(index)"
          ></image>
          
          <!-- 视频播放器 -->
          <video
              v-if="index === currentVideoIndex && !!video.videoUrl"
              :id="`video-${video.id || index}`"
              class="video-player"
              :src="video.videoUrl"
              :poster="video.coverUrl"
              controls
              :autoplay="false"
              :show-center-play-btn="false"
              :show-fullscreen-btn="false"
              :enable-progress-gesture="true"
              @play="onPlay(index)"
              @pause="onPause(index)"
              :duration="video.duration"
              @ended="onEnded(index)"
              @click="togglePlay(index)"
              @error="onVideoError(index, $event)"
              @loadedmetadata="onLoaded(index, $event)"
            ></video>

          <!-- 视频信息 -->
          <view class="video-info">
            <text class="video-title">{{ video.title }}</text>
            <text class="video-description">{{ video.description }}</text>
            <text class="video-duration">时长: {{ formatDuration(video.duration) }}</text>
            <text class="video-view-count">播放量: {{ video.viewCount }}</text>

            <!-- 互动按钮 -->
            <view class="interaction-buttons">
              <view class="button-item" @click="handleLike(index)">
                <uni-icons class="button-icon" :type="video.is_liked ? 'heart-filled' : 'heart'" :size="30" :color="video.is_liked ? '#ff0000' : '#ffffff'"></uni-icons>
                <text class="button-text">{{ video.likeCount }}</text>
              </view>
              <view class="button-item" @click="handleFavorite(index)">
                <uni-icons class="button-icon" :type="video.is_favorited ? 'star-filled' : 'star'" :size="30" :color="video.is_favorited ? '#ffcc00' : '#ffffff'"></uni-icons>
                <text class="button-text">{{ video.favoriteCount }}</text>
              </view>
              <view class="button-item" @click="handleComment(index)">
                <uni-icons class="button-icon" type="chatbubble" size="30" color="#ffffff"></uni-icons>
                <text class="button-text">{{ video.comment_count }}</text>
              </view>
            </view>
          </view>
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
import { getVideoList } from '@/api/video'

export default {
  data() {
    return {
      videoList: [],
      currentVideoIndex: 0,
      autoPlayTimer: null // 用于自动播放的定时器
    }
  },
  onLoad() {
    this.fetchVideoList().then(() => {
      // 启动自动播放功能
      this.startAutoPlay()
    })
  },
  beforeDestroy() {
    // 清理定时器
    if (this.autoPlayTimer) {
      clearTimeout(this.autoPlayTimer);
      this.autoPlayTimer = null;
    }
  },
  methods: {
    // 获取视频列表
    async fetchVideoList() {
      try {
        const res = await getVideoList()
        if (res.code === 200) {
          // 接口返回的数据格式为 { code: 200, data: [{ ... }, { ... }] }
          this.videoList = res.data || []
          // 处理视频数据，确保字段名称匹配
          this.videoList.forEach(video => {
            // 字段标准化
            video.videoUrl = (video.videoUrl || '').trim();
            video.coverUrl = (video.coverUrl || '').trim();
            video.likeCount = video.likeCount || 0;
            video.favoriteCount = video.favoriteCount || 0;
            video.viewCount = video.viewCount || 0;
            video.duration = video.duration || 0;
            video.status = video.status || 1;
            
            // 交互状态
            video.is_liked = false;
            video.is_favorited = false;
            video.comment_count = video.comment_count || 0;
            
            // 播放状态
            video.playing = false;
            video.showCover = true;
            
            // // 确保视频路径和封面路径正确
            // if (video.video_path && !video.video_path.startsWith('http')) {
            //   // 可以根据实际情况添加基础URL前缀
          // video.videoUrl = 'https://your-domain.com/' + video.videoUrl
            // }
            // if (video.cover_path && !video.cover_path.startsWith('http')) {
            //   // 可以根据实际情况添加基础URL前缀
          // video.coverUrl = 'https://your-domain.com/' + video.coverUrl
            // }
          })
          console.log('视频列表数据:', this.videoList)
        } else {
          uni.showToast({
            title: '获取视频列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取视频列表异常:', error)
        uni.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        })
      }
    },

    // 格式化时长
    formatDuration(seconds) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    },

    // 滑动切换视频
    onSwipeChange(e) {
      const newIndex = e.detail.current
      this.currentVideoIndex = newIndex

      // 暂停其他视频并重置封面
      this.pauseOthers(newIndex)

      // 启动新视频的自动播放功能
      this.startAutoPlay()

      // 当滑动到最后一个视频时，加载更多
      if (newIndex === this.videoList.length - 1) {
        this.loadMoreVideos()
      }
    },

    // 加载更多视频
    async loadMoreVideos() {
      // 这里可以实现分页加载逻辑
      // 为了简单起见，这里暂时不实现
    },
    
    // 启动自动播放功能
    startAutoPlay() {
      // 清除之前的定时器
      if (this.autoPlayTimer) {
        clearTimeout(this.autoPlayTimer);
        this.autoPlayTimer = null;
      }
      
      // 设置1秒后自动播放
      this.autoPlayTimer = setTimeout(() => {
        if (this.videoList.length > 0 && this.currentVideoIndex < this.videoList.length) {
          this.playVideo(this.currentVideoIndex);
        }
        this.autoPlayTimer = null;
      }, 1000);
    },

    // 播放日志（保留原逻辑，避免与真正的 onPlay 重名）
    _onPlayLog(index) {
      // 设置播放状态为true，隐藏封面（仅日志方法，不在模板中绑定）
      this.videoList[index].playing = true;
      console.log('视频开始播放，index:', index, 'playing状态:', this.videoList[index].playing);
      if (this.autoPlayTimer) {
        clearTimeout(this.autoPlayTimer);
        this.autoPlayTimer = null;
      }
    },
    
    // 页面显示时确保当前视频封面状态正确
    onShow() {
      // 确保当前视频的封面状态正确
      if (this.videoList.length > 0 && this.currentVideoIndex < this.videoList.length) {
        // 强制更新组件以反映正确的播放状态
        this.$forceUpdate();
        
        // 如果视频应该在播放状态，确保实际播放
        if (this.videoList[this.currentVideoIndex].playing) {
          const cur = this.videoList[this.currentVideoIndex]
          const videoContext = uni.createVideoContext(`video-${(cur && cur.id) ?? this.currentVideoIndex}`, this);
          videoContext.play();
        }
      }
    },

    // 视频播放结束
    onEnded(index) {
      console.log('视频播放结束，index:', index);
      // 自动播放下一个视频
      if (index < this.videoList.length - 1) {
        this.currentVideoIndex = index + 1
        // 启动下一个视频的自动播放功能
        this.startAutoPlay()
      } else {
        // 最后一个视频播放结束，重置播放状态以便重新播放
        this.videoList[index].playing = false;
        console.log('最后一个视频播放结束，重置playing状态');
        // 可以选择循环播放或加载更多
        // this.currentVideoIndex = 0; // 循环播放
        // this.loadMoreVideos(); // 加载更多
      }
    },
    
    // 播放视频
    playVideo(index) {
      const item = this.videoList[index]
      if (!item || !item.videoUrl) {
        uni.showToast({ title: '该视频暂无地址', icon: 'none' })
        return
      }
      console.log('播放视频，index:', index, 'src:', item.videoUrl);
      // 立即标记为播放，卸载封面，避免看不到画面
      this.$set(this.videoList[index], 'playing', true)
      this.$set(this.videoList[index], 'showCover', false)
      
      // 暂停其他视频
      this.pauseOthers(index)

      // 强制更新组件以确保UI反映正确的播放状态
      this.$forceUpdate();
      
      // 创建视频上下文并控制播放
      const videoContext = uni.createVideoContext(`video-${(item && item.id) ?? index}` , this);
      videoContext.play();
    },
    
    // 切换视频播放状态（暂停/恢复）
    togglePlay(index) {
      const video = this.videoList[index];
      if (!video || !video.videoUrl) {
        uni.showToast({ title: '该视频暂无地址', icon: 'none' })
        return
      }
      // 切换播放状态
      video.playing = !video.playing;
      console.log('切换视频播放状态，index:', index, 'playing状态:', video.playing);
      // 当切到播放时，确保封面关闭；切到暂停时不显示封面
      if (video.playing && video.showCover) {
        this.$set(this.videoList[index], 'showCover', false)
      }
      
      // 强制更新组件以确保UI反映正确的播放状态
      this.$forceUpdate();
      
      // 创建视频上下文并控制播放/暂停
      const videoContext = uni.createVideoContext(`video-${(video && video.id) ?? index}`, this);
      if (video.playing) {
        videoContext.play();
      } else {
        videoContext.pause();
      }
    },

    // 暂停除当前外的所有视频，重置封面
    pauseOthers(activeIndex) {
      this.videoList.forEach((v, i) => {
        if (i !== activeIndex) {
          v.playing = false
          const ctx = uni.createVideoContext(`video-${(v && v.id) ?? i}`, this)
          // try-catch 防止个别平台报错
          try { ctx.pause() } catch (e) {}
        }
      })
    },

    // 视频加载元数据（时长、尺寸）
    onLoaded(index, e) {
      console.log('loadedmetadata index=', index, e && e.detail)
    },

    // 视频播放错误
    onVideoError(index, e) {
      const detail = (e && e.detail) || e
      console.error('video error index=', index, detail)
      uni.showToast({
        title: `第${index + 1}个视频加载失败`,
        icon: 'none'
      })
    },

    // 播放事件兜底，确保状态为播放
    onPlay(index) {
      if (this.videoList[index]) {
        if (!this.videoList[index].playing) {
          this.$set(this.videoList[index], 'playing', true)
        }
        // 一旦开始播放，隐藏封面；后续暂停也不再出现封面
        if (this.videoList[index].showCover) {
          this.$set(this.videoList[index], 'showCover', false)
        }
      }
      // 清除自动播放定时器
      if (this.autoPlayTimer) {
        clearTimeout(this.autoPlayTimer);
        this.autoPlayTimer = null;
      }
    },

    // 暂停事件：恢复封面
    onPause(index) {
      if (this.videoList[index]) {
        this.$set(this.videoList[index], 'playing', false)
      }
    },

    // 点赞
    handleLike(index) {
      const video = this.videoList[index]
      video.is_liked = !video.is_liked
      if (video.is_liked) {
        video.likeCount += 1
      } else {
        video.likeCount -= 1
      }
      // 这里可以调用点赞接口
    },

    // 收藏
    handleFavorite(index) {
      const video = this.videoList[index]
      video.is_favorited = !video.is_favorited
      if (video.is_favorited) {
        video.favoriteCount += 1
      } else {
        video.favoriteCount -= 1
      }
      // 这里可以调用收藏接口
    },

    // 评论
    handleComment(index) {
      // 跳转到评论页面
      uni.navigateTo({
        url: `/pages/comment/index?videoId=${this.videoList[index].id}`
      })
    }
  }
}
</script>

<style scoped>
.video-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.video-swiper {
  width: 100%;
  height: 100%;
}

.video-item {
  width: 100%;
  height: 100%;
  position: relative;
}

.video-player {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.video-cover {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  transition: opacity 0.3s ease;
  opacity: 1;
}

.video-cover.hidden {
  opacity: 0;
  pointer-events: none;
}

.video-info {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 20rpx;
  box-sizing: border-box;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
  color: #fff;
}

.video-title {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.video-description {
  font-size: 28rpx;
  display: block;
  margin-bottom: 10rpx;
  line-height: 1.4;
}

.video-duration,
.video-view-count {
  font-size: 24rpx;
  display: block;
  margin-bottom: 8rpx;
  opacity: 0.9;
}

.interaction-buttons {
  display: flex;
  justify-content: flex-end;
  padding-right: 30rpx;
  margin-bottom: 20rpx;
}

.button-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-left: 40rpx;
}

.button-icon {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 10rpx;
}

.button-text {
  font-size: 24rpx;
  color: #fff;
}
</style>